<?php
include("./api.inc.php");
require './config.php';
$fkh_kg = $DB->get_row("SELECT * FROM auth_pay WHERE k='khd_kg'");
if ($fkh_kg['v'] == 1) {
    $km = $_GET['km'];
    $ip = $_SERVER['REMOTE_ADDR'];
    $date = date("Y-m-d H-i-s");
    $row2 = $DB->get_row("SELECT * FROM auth_kms WHERE VisitorIp='{$ip}'");
    $row = $DB->get_row("SELECT * FROM auth_kms WHERE km = '{$km}'");
    if ($km == '' || $ip == '') {
        $arr = array("code" => 201, "msg" => "请确保所需参数无误");
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
    if (!$row) {
        $arr = array("code" => 201, "msg" => "此授权码不存在");
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    } else if ($row['Expiration'] != NULL && $row['Expiration'] < time()) {
        $arr = array("code" => 201, "msg" => "此授权码已失效");
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
    $daili_id = $row['daili_id']; // 获取卡密的daili_id
// 查询这个daili_id的endtime是否小于当前时间
    $result = $DB->get_row("SELECT endtime FROM auth_user WHERE uid = $daili_id");
//$result = $query->fetch(PDO::FETCH_ASSOC);
    if ($result['endtime'] != NULL && $result['endtime'] < time()) {
        $arr = array("code" => 201, "msg" => "代理卡密已过期");
        exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
    if ($row['type'] == 'ClassB_1') {
        if ($row['VisitorIp'] != '' && $row['VisitorIp'] != $ip) {
            $arr = array("code" => 201, "msg" => "此授权码已被使用");
            exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        } else {
            $Expiration = strtotime("+2 hours");
        }
    } elseif ($row['type'] == 'ClassB_30') {
        $Expiration = strtotime("+30 day");
    } elseif ($row['type'] == 'ClassB_90') {
        $Expiration = strtotime("+90 day");
    } elseif ($row['type'] == 'ClassB_365') {
        $Expiration = strtotime("+365 day");
    }
    $DB->query("UPDATE `auth_kms` SET `zt` = '已激活', `VisitorIp` = '" . $_SERVER['REMOTE_ADDR'] . "', `Expiration` = '" . $Expiration . "', `activation` = '" . time() . "' WHERE `auth_kms`.`id` = " . $row['id']);
    $arr = array("code" => 200, "msg" => "已激活");
    exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
} else {
    $arr = array("code" => 200, "msg" => "已激活,关闭验证");
    exit(json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
?>